package net.example.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.oraycn.esbasic.views.AutoNewLineLayout;
import com.oraycn.omcs.ICamOpenOverCallback;
import com.oraycn.omcs.MultimediaManagerFactory;
import com.oraycn.omcs.core.CameraSurfaceView;
import com.oraycn.omcs.mulitChat.ChatType;
import com.oraycn.omcs.mulitChat.IChatGroup;
import com.oraycn.omcs.mulitChat.IChatGroupEventListener;
import com.oraycn.omcs.mulitChat.IChatUnit;
import net.example.activity.view.OMCSSurfaceViewPlus;
import net.example.manager.ClientGlobalCache;
import net.example.manager.Manager;
import net.example.manager.GGApplication;
import net.example.model.CommunicateMediaType;
import net.example.model.CommunicateType;
import net.example.model.event.CallEvent;
import net.example.ggtalk.R;
import net.example.utils.CommonHelper;
import net.example.utils.LogHelper;
import net.example.utils.ToastUtils;
import net.example.utils.android.AndroidUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;


public class VideoChat4GroupActivity extends Activity implements ICamOpenOverCallback {
    CameraSurfaceView myCameraSurfaceView = null;
    ImageView hang_up, convert_camera ;
    Button switch_to_mute,switch_to_Handsfree,switch_to_openCamera;
    int currentCamIndex = 1;
    String groupid = "";
    String tag="";//创建群聊天时从ChatActivity界面传过来的
    private int currVolume=0;//当前音量
    LinearLayout layout_buttom,layout_middle;
    IChatGroup chatGroup ;
    AutoNewLineLayout camera_container;
    HashMap<String , ViewGroup> cameraMap=new HashMap<>();
    List<String> memberIDs=new ArrayList<String>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_chat4_group);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        Intent intent =getIntent();
        this.groupid = intent.getStringExtra("groupID");
        this.tag=intent.getStringExtra("tag");
        memberIDs=intent.getStringArrayListExtra("memberIDs");
        LogHelper.e("groupid:"+this.groupid);
        this.init();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(this.memberIDs==null||this.memberIDs.isEmpty())
        {
            return;
        }
        //发送群视频请求
        for (String id : this.memberIDs){
            if(id.equals(ClientGlobalCache.getInstance().getCurrentUser().getUserID())){continue;}
            Manager.getInstance().sendMediaCommunicate(id, CommunicateMediaType.GroupVideo, CommunicateType.Request,this.tag,-1);
        }
    }

    private void init()
    {
        try {
            MultimediaManagerFactory.GetSingleton().setCameraOpenCallBack(this);
            //显示本地数据view
            myCameraSurfaceView = (CameraSurfaceView) findViewById(R.id.group_camera_surfaceview_local);
            TextView mytext=(TextView) findViewById(R.id.tv_userID);
            mytext.setText(ClientGlobalCache.getInstance().getUserName(CommonHelper.getUserID4OMCS(MultimediaManagerFactory.GetSingleton().getCurrentUserID())));
            layout_buttom = (LinearLayout) findViewById(R.id.layout_bottom);
            layout_middle =(LinearLayout) findViewById(R.id.layout_middle);
            View view= findViewById(R.id.group_video_session);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    boolean isGone=layout_buttom.getVisibility()== View.GONE;
                    layout_buttom.setVisibility(isGone? View.VISIBLE:View.GONE);
                    layout_middle.setVisibility(isGone? View.VISIBLE:View.GONE);
                }
            });
            camera_container =(AutoNewLineLayout)findViewById(R.id.camera_container);
            convert_camera = (ImageView) findViewById(R.id.group_convert_camera);
            switch_to_mute=(Button) findViewById(R.id.switch_to_mute);
            switch_to_Handsfree=(Button)findViewById(R.id.switch_to_Handsfree);
            switch_to_openCamera=(Button)findViewById(R.id.switch_to_openCamera);
            //默认开启声音和视频
            MultimediaManagerFactory.GetSingleton().setOutputAudio(true);
            MultimediaManagerFactory.GetSingleton().setOutputVideo(true);
            // myView.setZ(1);
            //显示对方数据view
            setButtonEvent();
            setHangUp();
            setConvertCamera();
            beginConnect();
            GGApplication.getInstance().ringForCalling();
        } catch
        (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MultimediaManagerFactory.GetSingleton().setOutputAudio(true);
        MultimediaManagerFactory.GetSingleton().setOutputVideo(true);
        GGApplication.getInstance().stopRingForCalling();
        EventBus.getDefault().unregister(this);
    }

    //region ICamOpenOverCallback
    @Override
    public void cameraHasOpened() {
        try {
            //预览camera所用holder,不可为null或是隐藏，否则不能从摄像头获取数据
            SurfaceHolder holder = myCameraSurfaceView.getSurfaceHolder();
            MultimediaManagerFactory.GetSingleton().startCameraPreview(holder);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void cameraOpenFailed(Exception e) {
        e.printStackTrace();
    }
    //endregion

    private void setHangUp() {
        hang_up = (ImageView) findViewById(R.id.group_hung_up);
        //挂断
        hang_up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MultimediaManagerFactory.GetSingleton().getGroupEntrance().exit(ChatType.Video, groupid);
                removeAllMemberView();
                finish();
            }
        });
    }

    private void setConvertCamera() {
        //切换摄像头
        convert_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                convertCameraIndex();
            }
        });
    }

    private void beginConnect() {
        try {
            setChatGroup();
            for ( IChatUnit unit : chatGroup.getOtherMembers()) {
                addMemberView(unit);
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    //切换摄像头
    private void convertCameraIndex() {
        try {
            ++currentCamIndex;
            //切换摄像头
            MultimediaManagerFactory.GetSingleton().switchCameraDeviceIndex(currentCamIndex % 2);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void setButtonEvent()
    {
        //静音
        switch_to_mute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isMute = switch_to_mute.isActivated();
                MultimediaManagerFactory.GetSingleton().setOutputAudio(isMute);//true :开起声音， false：静音
                switch_to_mute.setActivated(!isMute);
            }
        });

        //免提
        switch_to_Handsfree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isHandsfree=false;
                if(currVolume==0){
                    currVolume = AndroidUtil.OpenSpeaker(VideoChat4GroupActivity.this);
                    isHandsfree=true;
                }else{
                    AndroidUtil.CloseSpeaker(VideoChat4GroupActivity.this,currVolume);
                    currVolume=0;
                    isHandsfree=false;
                }
                switch_to_Handsfree.setActivated(isHandsfree);
            }
        });

        //打开摄像头
        switch_to_openCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isOpenCamera = !switch_to_openCamera.isActivated();
                MultimediaManagerFactory.GetSingleton().setOutputVideo(isOpenCamera);
                switch_to_openCamera.setActivated(isOpenCamera);
            }
        });
        switch_to_openCamera.performClick();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    removeMemberView((IChatUnit) msg.obj);
                    break;
                case 0: {
                    IChatUnit chatUnit=(IChatUnit) msg.obj;
                    addMemberView(chatUnit);
                    ToastUtils.showShort(VideoChat4GroupActivity.this, ClientGlobalCache.getInstance().getUserName(CommonHelper.getUserID4OMCS(chatUnit.getMemberID())) + "加入群视频聊天!");
                    break;
                }
            }
        }

    };

    //设置并加入群聊组
    private void setChatGroup() {
        LogHelper.i("加入Groupid："+this.groupid);
        chatGroup =MultimediaManagerFactory.GetSingleton().getGroupEntrance().join(ChatType.Video, this.groupid);
        chatGroup.setChatGroupEventListener(new IChatGroupEventListener() {
            @Override
            public void someoneJoin(IChatUnit unit) {
                Message msg = new Message();
                msg.obj = unit;
                msg.what = 0;
                mHandler.sendMessage(msg);
            }
            @Override
            public void someoneExit(IChatUnit unit) {
                Message msg = new Message();
                msg.what = 1;
                msg.obj=unit;
                mHandler.sendMessage(msg);
            }
        });
    }

    //添加指定对象的视频
    private void addMemberView(final IChatUnit unit) {
        OMCSSurfaceViewPlus omcs_surface_plus = new OMCSSurfaceViewPlus(VideoChat4GroupActivity.this);
        omcs_surface_plus.initialize(unit,false);
        camera_container.addView(omcs_surface_plus);
        cameraMap.put(unit.getMemberID(), omcs_surface_plus);
    }

    //移除指定对象的视频
    private void removeMemberView(IChatUnit chatUnit)
    {
        if(chatUnit!=null)
        {
            chatUnit.cameraConnector().disconnect();
            chatUnit.microphoneConnector().disconnect();
        }
        ViewGroup layout= cameraMap.get(chatUnit.getMemberID());
        if(layout!=null)
        {
            layout.setVisibility(View.GONE);
            camera_container.removeView(layout);
        }
        cameraMap.remove(chatUnit.getMemberID());
        ToastUtils.showShort(this, ClientGlobalCache.getInstance().getUserName(CommonHelper.getUserID4OMCS(chatUnit.getMemberID())) + "退出群视频聊天!");
    }
    //移除所有连接的视频
    private void removeAllMemberView()
    {
        for (IChatUnit chatUnit: chatGroup.getOtherMembers())
        {
            removeMemberView(chatUnit);
        }
        cameraMap.clear();
    }

    public void onEventMainThread(CallEvent event) {
        if(event.mediaType!= CommunicateMediaType.GroupVideo)
        {
            return;
        }
        if(!event.Tag.equals(this.groupid))
        {return;}
        String omcsUserName=ClientGlobalCache.getInstance().getUserName(CommonHelper.getUserID4OMCS(event.target));
        if (event.communicateType == CommunicateType.Agree) {
            GGApplication.getInstance().stopRingForCalling();//若有一位成员加入则关闭请求声音
        } else if (event.communicateType == CommunicateType.Reject) {
            ToastUtils.singleShow(VideoChat4GroupActivity.this, omcsUserName + "拒绝了群视频邀请!");
            LogHelper.i(omcsUserName + "拒绝了群视频邀请!");
         //   Toast.makeText(VideoChat4GroupActivity.this, omcsUserName + "拒绝了群视频邀请!", Toast.LENGTH_LONG).show();
//            ToastUtils.singleShow(this, ClientGlobalCache.getInstance().getUserName(event.target) + "拒绝了群视频邀请!");
        } else if (event.communicateType == CommunicateType.Terminate) {
            ToastUtils.showShort(this, omcsUserName + "视频已中断!");
        } else if (event.communicateType == CommunicateType.Busy) {
            ToastUtils.showShort(this, omcsUserName + "忙线中!");
        }
    }

}